package com.jackchong.utils

import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer

/**
 * author : chong.huang
* create : 5/28/21
 * desc   :
 */
open class JLiveData<T> : MutableLiveData<T> {

    constructor(): super()

    constructor(value: T?): super(value)

    override fun getValue(): T? {
        return super.getValue()
    }


    override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
        super.observe(owner, observer)
    }

    fun observeNotNull(owner: LifecycleOwner, observer: Observer<in T>) {
        super.observe(owner, Observer<T> { t ->
            observer.onChanged(t?: return@Observer)
        })
    }

    fun observeSingle(owner: LifecycleOwner, observer: Observer<in T>) {
        super.observe(owner, object : Observer<T> {
                override fun onChanged(t: T) {
                    removeObserver(this)
                    observer.onChanged(t)
                }
            }
        )
    }

    fun observeSingleNotNull(owner: LifecycleOwner, observer: Observer<in T>) {
        super.observe(owner, object : Observer<T> {
                override fun onChanged(t: T) {
                    if (t != null) {
                        removeObserver(this)
                        observer.onChanged(t)
                    }
                }
            }
        )
    }


}